<script setup>
import {reactive, ref} from "vue";
import axios from "axios";
import xx from "@/axios/xx";
import {ElMessage} from "element-plus";
import {Delete, Download, Edit, Plus, Search, Upload} from "@element-plus/icons-vue";

let info = reactive({
  list:[],//列表数据
  form:{},//表单数据
  dialogVisible:false,//对话框数据
  pageNum: 1, //当前页
  pageSize: 5, //每页大小
  total: 0,//总条数
  isAdd: true,//增加和修改标识
  bankList:[],//银行所有数据
  importDialogVisible:false,//导入对话框是否显示
  importExcelUrl:"",//导入Excel地址
})
info.importExcelUrl = xx.defaults.baseURL + "bank/importExcel";


//新增按钮点击方法
const Add = () => {
  info.dialogVisible = true
  info.isAdd = true
}
//查询列表信息
const load = () => {
  xx.get('/bank',{
    params:{
      pageNum:info.pageNum,
      pageSize:info.pageSize,
      bankName:info.form.bankName,
    }
  }).then(res =>{
    console.log(res)
    info.list = res.data.list
    //当前页
    info.pageNum = res.data.pageNum;
    //每页大小
    info.pageSize = res.data.pageSize;
    //总条数
    info.total = res.data.total;
  })
}

load()

//分页当前页改变
const handleCurrentChange = (pageNum) => {
  info.pageNum = pageNum;
  load()
}

//分页大小改变
const handleSizeChange = (pageSize) => {
  info.pageSize = pageSize;
  load()
}



//删除
const handleDelete = (bankId) => {
  xx.delete('/bank/'+bankId).then(res => {
    console.log(res)
    if(res.code === 200){
      ElMessage({
        message: res.message,
        type:'success',
      })
    }else {
      ElMessage.error(res.message)
    }
    load()
  })
}

//持久化数据
const persistence = () => {
  xx({
    url:'/bank',
    method:info.isAdd?'post':'put',
    data:info.form
  }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: res.message,
        type: 'success',
      })
    } else {
      ElMessage.error(res.message)
    }
    //关闭对话框
    info.dialogVisible = false
    info.form = {} //情况数据
    load()
  })
}
//点击修改按钮  - 根据id查询对应的数据
const handleEdit = (bankId) => {
  info.isAdd = false
  xx.get('/bank/'+bankId).then(res => {
    info.form = res.data
    info.dialogVisible = true
  })
}
//关闭对话框，清空数据
const handleClose = () => {
  info.form = {}
  info.dialogVisible = false
}

//导出数据
const exportExcel = () => {
  xx({
    method:"get",
    url:"/bank/exportExcel",
    params:{
      pageNum:info.pageNum,
      pageSize:info.pageSize,
      bankName:info.form.bankName,
    },
    responseType:"blob" //定义为bolb
  }).then(res =>{
    let blob = new Blob([res])
    let downloadElement = document.createElement('a')
    let href = window.URL.createObjectURL(blob) // 创建下载的链接
    downloadElement.href = href
    downloadElement.download = '银行信息数据.xlsx' // 下载后文件名
    document.body.appendChild(downloadElement)
    downloadElement.click() // 点击下载
    document.body.removeChild(downloadElement) // 下载完成移除元素
    window.URL.revokeObjectURL(href) // 释放掉blob对象
  })
}

//导入数据
const importExcel = () => {
  info.importDialogVisible = true;
}
const upload = ref()
//处理文件覆盖
const handleExceed = (files) => {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}
//确认导入数据
const submitUpload = () => {
  upload.value.submit()
}
//导入前判断文件类型
const beforeUpload = (rawFile) => {
  const allowedTypes = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
  const isAllowedType = allowedTypes.some(type => rawFile.type.startsWith(type));

  if (!isAllowedType) {
    ElMessage.error('只能上传 .xlsx、.xls 文件类型');
    return false;
  }
  return true;
}
//导入成功之后
const handleSuccess = (response, uploadFile) => {
  if(response.code == 200){
    ElMessage({
      type: 'success',
      message: response.message,
    })
    //关闭对话框
    info.importDialogVisible = false;
    //清空数据
    info.form = {}
    //重新加载
    load()
  } else {
    ElMessage.error(response.message)
  }
}

</script>

<template>
  <div class="bankInfo">
    <!--增加按钮-->
    <el-button type="success" @click="Add"><el-icon class="el-icon--left" ><Plus /></el-icon>新增银行信息</el-button>
    <el-button type="danger" @click="exportExcel"><el-icon class="el-icon--left" ><Download /></el-icon>导出数据</el-button>
    <el-button type="danger" @click="importExcel"><el-icon class="el-icon--left" ><Upload /></el-icon>导入数据</el-button>
    <br>
    <br>
    <!--快捷查询-->
    <el-form :inline="true" :model="info.form" class="demo-form-inline">
      <el-form-item label="银行名称：">
        <el-input v-model="info.form.bankName"  placeholder="模糊查询" clearable >
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="load" :icon="Search">查询</el-button>
      </el-form-item>
    </el-form>
    <!--表格信息-->
    <el-table :data="info.list" border stripe style="width: 100%">
      <el-table-column type="index" align="center" label="序号" width="100" />
      <el-table-column prop="bankName" align="center" label="银行" width="180" />
      <el-table-column prop="bankAddress" align="center" label="银行地址"  />
      <el-table-column prop="phoneNumber" align="center" label="联系电话" width="150" />
      <el-table-column prop="email" align="center" label="电子邮件" width="220" />
      <el-table-column prop="website" align="center" label="官网地址" width="220"/>
      <el-table-column prop="establishedYear" align="center" label="成立年份" width="160" />
      <el-table-column align="center" label="操作" width="200" >
        <template #default="scope">
          <el-button size="small" style="background-color: bisque" @click="handleEdit(scope.row.bankId)"><el-icon class="el-icon--left" ><Edit /></el-icon>
            修改 </el-button>
          <el-popconfirm @confirm="handleDelete(scope.row.bankId)" title="你确定要删除吗?">
            <template #reference>
              <el-button size="small" type="danger" ><el-icon class="el-icon--left" ><Delete /></el-icon>
                删除 </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <br>
    <div class="demonstration"></div>
    <el-pagination
        v-model:current-page="info.pageNum"
        v-model:page-size="info.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :small="false"
        :disabled="false"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="info.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <!--窗口-->
  <el-dialog
      v-model="info.dialogVisible"
      :title="info.isAdd ? '新增银行信息' : '修改银行信息'"
      width="40%"
      :before-close="handleClose"
  >
    <el-form :model="info.form" label-width="auto" style="max-width: 90%;margin-left: 20px">
      <el-form-item label="银行">
        <el-input v-model="info.form.bankName" />
      </el-form-item>
      <el-form-item label="银行地址">
        <el-input v-model="info.form.bankAddress" />
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input v-model="info.form.phoneNumber" />
      </el-form-item>
      <el-form-item label="电子邮件">
        <el-input v-model="info.form.email" />
      </el-form-item>
      <el-form-item label="官网地址">
        <el-input v-model="info.form.website" />
      </el-form-item>
      <el-form-item label="成立年份">
        <el-input v-model="info.form.establishedYear" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="persistence" > 保存信息 </el-button>
      </div>
    </template>
  </el-dialog>

  <!--  导入数据 dialog对话框窗口-->
  <el-dialog v-model="info.importDialogVisible" title="银行信息数据导入" :before-close="handleClose1" width="45%">
    <el-upload
        ref="upload"
        class="upload-demo"
        :action="info.importExcelUrl"
        :limit="1"
        :on-exceed="handleExceed"
        :auto-upload="false"
        :before-upload="beforeUpload"
        :on-success="handleSuccess"
    >
      <template #trigger>
        <el-button type="primary">选择文件</el-button>
      </template>
      &nbsp;&nbsp;&nbsp;&nbsp;
      <el-button class="ml-3" type="success" @click="submitUpload">
        导入数据
      </el-button>
      <template #tip>
        <div class="el-upload__tip text-red" style="color: #f63636;">
          一次只能导入一个文件，类型为 .xlsx 格式
        </div>
      </template>
    </el-upload>
  </el-dialog>

</template>

<style scoped>

</style>